package org.linlinjava.litemall.wx.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.LitemallGoodsProductService;
import org.linlinjava.litemall.db.service.LitemallGoodsService;
import org.linlinjava.litemall.db.service.LitemallGoodsAttributeService;
import org.linlinjava.litemall.db.service.LitemallPermissionService;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.vo.GoodsProduct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;


import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/wx/publish")
@Validated
public class WxPublishController {
    private final Log logger = LogFactory.getLog(WxPublishController.class);

    @Autowired
    private LitemallGoodsService goodsService;

    @Autowired
    private LitemallGoodsAttributeService goodsAttributeService;

    @Autowired
    private LitemallGoodsProductService goodsProductService;
    /**
     * 获取用户发布的商品列表
     */
    @GetMapping("/list")
    public Object list(Integer userId) {
        if (userId == null || userId == 0) {
            return ResponseUtil.unlogin();
        }

        try {
            // 先查询属性表获取该用户发布的商品ID列表
            LitemallGoodsAttributeExample attributeExample = new LitemallGoodsAttributeExample();
            attributeExample.or()
                    .andAttributeEqualTo("userId")  // 注意这里的属性名要与数据库中的一致
                    .andValueEqualTo(String.valueOf(userId))
                    .andDeletedEqualTo(false);

            List<LitemallGoodsAttribute> attributes = goodsAttributeService.queryByExample(attributeExample);

            if (attributes.isEmpty()) {
                return ResponseUtil.okList(new ArrayList<>());
            }

            // 获取商品ID列表
            List<Integer> goodsIds = attributes.stream()
                    .map(LitemallGoodsAttribute::getGoodsId)
                    .collect(Collectors.toList());

            // 查询商品详情
            LitemallGoodsExample goodsExample = new LitemallGoodsExample();
            goodsExample.or()
                    .andIdIn(goodsIds)
                    .andDeletedEqualTo(false);

            List<LitemallGoods> goodsList = goodsService.queryByExample(goodsExample);

            // 转换为前端需要的格式
            List<Map<String, Object>> result = goodsList.stream().map(goods -> {
                Map<String, Object> map = new HashMap<>();
                map.put("id", goods.getId());
                map.put("name", goods.getName());
                map.put("brief", goods.getBrief());
                map.put("picUrl", goods.getPicUrl());
                map.put("counterPrice", goods.getCounterPrice());
                map.put("retailPrice", goods.getRetailPrice());
                return map;
            }).collect(Collectors.toList());

            return ResponseUtil.okList(result);
        } catch (Exception e) {
            logger.error("获取用户[" + userId + "]发布商品列表失败: " + e.getMessage(), e);
            return ResponseUtil.serious();
        }
    }

    /**
     * 获取商品详情
     */
    @GetMapping("/detail/{userId}/{id}")
    public Object detail(@PathVariable(name = "userId") Integer userId,@PathVariable @NotNull Integer id) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        try {
            // 验证商品是否属于该用户
            LitemallGoodsAttribute attribute = goodsAttributeService.findByGoodsIdAndAttribute(id, "userId");
            if (attribute == null || !attribute.getValue().equals(String.valueOf(userId))) {
                return ResponseUtil.fail(403, "无权限查看此商品");
            }

            // 获取商品详情
            LitemallGoods goods = goodsService.findById(id);
            List<LitemallGoodsProduct> litemallGoodsProducts = goodsProductService.queryByGid(goods.getId());
            if (goods == null || goods.getDeleted()) {
                return ResponseUtil.fail(404, "商品不存在");
            }
            System.out.println(goods);
            Map<String, Object> data = new HashMap<>();
            data.put("id", goods.getId());
            data.put("name", goods.getName());
            data.put("brief", goods.getBrief());
            data.put("picUrl", goods.getPicUrl());
            data.put("counterPrice", goods.getCounterPrice());
            data.put("number",litemallGoodsProducts.get(0).getNumber());

            return ResponseUtil.ok(data);
        } catch (Exception e) {
            logger.error("获取商品详情失败", e);
            return ResponseUtil.serious();
        }
    }

    /**
     * 更新商品信息
     */
    @CacheEvict(value = {"goodsDetail", "goodsList"}, allEntries = true)
    @PostMapping("/update/{userId}/{number}")
    public Object update(@PathVariable Integer userId,@PathVariable Integer number, @RequestBody LitemallGoods goods) {
        // 验证商品是否属于该用户
        LitemallGoodsAttribute attribute = goodsAttributeService.findByGoodsIdAndAttribute(goods.getId(), "userId");
        if (attribute == null || !attribute.getValue().equals(String.valueOf(userId))) {
            return ResponseUtil.fail(403, "无权限修改此商品");
        }
        // 验证商品是否存在
        LitemallGoods originalGoods = goodsService.findById(goods.getId());
        if (originalGoods == null || originalGoods.getDeleted()) {
            return ResponseUtil.fail(404, "商品不存在");
        }
        // 数据验证
        if (goods.getCounterPrice().compareTo(new BigDecimal(0)) <= 0) {
            return ResponseUtil.fail(403, "商品价格必须大于0");
        }
        // 更新商品信息
        try {
            originalGoods.setName(goods.getName());
            originalGoods.setBrief(goods.getBrief());
            originalGoods.setCounterPrice(goods.getCounterPrice());
            originalGoods.setRetailPrice(goods.getCounterPrice());
            originalGoods.setUpdateTime(LocalDateTime.now());
            goodsService.updateById(originalGoods);
            goodsProductService.updateByGid(new LitemallGoodsProduct(goods.getId(),number));
            return ResponseUtil.ok();
        } catch (Exception e) {
            logger.error("更新商品失败", e);
            return ResponseUtil.fail(500, "更新商品失败");
        }
    }

    /**
     * 删除商品
     */
    @CacheEvict(value = "goodsList", allEntries = true)
    @PostMapping("/delete/{userId}")
    @Transactional  // 添加事务注解确保数据一致性
    public Object delete(@PathVariable Integer userId, @RequestBody Map<String, Integer> body) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        Integer goodsId = body.get("goodsId");
        if (goodsId == null) {
            return ResponseUtil.badArgument();
        }

        // 验证商品是否属于该用户
        LitemallGoodsAttribute attribute = goodsAttributeService.findByGoodsIdAndAttribute(goodsId, "userId");
        if (attribute == null || !attribute.getValue().equals(String.valueOf(userId))) {
            return ResponseUtil.fail(403, "无权限删除此商品");
        }

        // 验证商品是否存在
        LitemallGoods goods = goodsService.findById(goodsId);
        if (goods == null || goods.getDeleted()) {
            return ResponseUtil.fail(404, "商品不存在");
        }

        try {
            // 物理删除商品
            goodsService.deleteById(goodsId);

            // 同时删除商品属性
            goodsAttributeService.deleteByGoodsIdPhysically(goodsId);

            return ResponseUtil.ok();
        } catch (Exception e) {
            logger.error("删除商品失败", e);
            return ResponseUtil.fail(500, "删除商品失败");
        }
    }
} 